import { BaseService, CoolCommException } from "@cool-midway/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { ProductRefundConfigEntity } from "../../entity/refund/config";
import { Inject, Provide } from "@midwayjs/core";
import { AddProductRefundConfigDTO } from "../../dto/refund/config";
import { ProductInfoEntity } from "../../entity/info";
import { Context } from "@midwayjs/koa";

@Provide()
export class ProductRefundConfigService extends BaseService {
    @InjectEntityModel(ProductRefundConfigEntity)
    productRefundConfigEntity: Repository<ProductRefundConfigEntity>;
    @InjectEntityModel(ProductInfoEntity)
    productInfoEntity: Repository<ProductInfoEntity>;

    @Inject()
    ctx: Context

    async add(dto: AddProductRefundConfigDTO) {
        const product = await this.productInfoEntity.findOne({ where: { id: dto.productId, tenantId: this.ctx.provider?.tenantId } });
        if (!product) {
            throw new CoolCommException('产品不存在');
        }
        const refundConfig = await this.productRefundConfigEntity.save({
            productId: dto.productId,
            type: dto.type,
            value: dto.value,
        });
        return refundConfig;
    }
}